{% extends "base.html" %}

{% block title %}XBot管理后台 - 用户管理{% endblock %}

{% block page_title_icon %}<i class="bi bi-person-badge page-title-icon"></i>{% endblock %}
{% block page_title %}用户管理{% endblock %}

{% block content %}
<!-- 操作区域 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="搜索用户..." id="searchInput">
            <button class="btn btn-primary" type="button" id="searchBtn">
                <i class="bi bi-search"></i> 搜索
            </button>
        </div>
    </div>
    <div class="col-md-4 text-end">
        <button class="btn btn-success" id="addUserBtn">
            <i class="bi bi-person-plus"></i> 添加用户
        </button>
    </div>
</div>

<!-- 用户列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">用户列表</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>用户名</th>
                        <th>角色</th>
                        <th>最后登录</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody">
                    <tr>
                        <td colspan="5" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2 text-muted">加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加/编辑用户模态框 -->
<div class="modal fade" id="userModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password">
                        <div class="form-text" id="passwordHelp">编辑用户时留空表示不修改密码</div>
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">角色</label>
                        <select class="form-select" id="role">
                            <option value="admin">管理员</option>
                            <option value="user">普通用户</option>
                            <option value="readonly">只读用户</option>
                        </select>
                    </div>
                    <div class="mb-3 form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="isActive" checked>
                        <label class="form-check-label" for="isActive">启用账户</label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                确定要删除用户 <strong id="deleteUsername"></strong> 吗？此操作无法撤销。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 全局变量
let usersList = [];
let currentUser = null;
let userModal = null;
let deleteModal = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化模态框
    userModal = new bootstrap.Modal(document.getElementById('userModal'));
    deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    
    // 加载用户列表
    loadUsers();
    
    // 绑定事件
    document.getElementById('addUserBtn').addEventListener('click', () => openUserModal());
    document.getElementById('saveUserBtn').addEventListener('click', saveUser);
    document.getElementById('confirmDeleteBtn').addEventListener('click', deleteUser);
    document.getElementById('searchBtn').addEventListener('click', searchUsers);
    document.getElementById('searchInput').addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            searchUsers();
        }
    });
});

// 加载用户列表
async function loadUsers() {
    const tableBody = document.getElementById('usersTableBody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2 text-muted">加载中...</p>
            </td>
        </tr>
    `;
    
    try {
        const response = await fetch('/api/users');
        const data = await response.json();
        
        if (data.success) {
            usersList = data.data || [];
            displayUsers(usersList);
        } else {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-4">
                        <div class="text-danger">
                            <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                            <p>加载失败: ${data.message || '未知错误'}</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载用户列表失败:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-danger">
                        <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                        <p>加载失败: ${error.message || '网络错误'}</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 显示用户列表
function displayUsers(users) {
    const tableBody = document.getElementById('usersTableBody');
    
    if (users.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-muted">
                        <i class="bi bi-people fs-3 mb-3"></i>
                        <p>暂无用户数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let html = '';
    
    users.forEach(user => {
        const statusBadge = user.is_active ? 
            '<span class="badge bg-success">已启用</span>' : 
            '<span class="badge bg-danger">已禁用</span>';
        
        const roleLabel = {
            'admin': '<span class="badge bg-primary">管理员</span>',
            'user': '<span class="badge bg-info">普通用户</span>',
            'readonly': '<span class="badge bg-secondary">只读用户</span>'
        }[user.role] || '<span class="badge bg-info">普通用户</span>';
        
        const lastLogin = user.last_login ? new Date(user.last_login).toLocaleString() : '从未登录';
        
        html += `
            <tr>
                <td>
                    <div class="d-flex align-items-center">
                        <div class="avatar bg-${user.is_active ? 'primary' : 'secondary'} rounded-circle me-2">
                            ${user.username.substring(0, 1).toUpperCase()}
                        </div>
                        <div>${user.username}</div>
                    </div>
                </td>
                <td>${roleLabel}</td>
                <td>${lastLogin}</td>
                <td>${statusBadge}</td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-primary" onclick="openUserModal('${user.username}')">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="confirmDeleteUser('${user.username}')" ${user.username === 'admin' ? 'disabled' : ''}>
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
}

// 打开用户模态框
function openUserModal(username = null) {
    const modalTitle = document.getElementById('userModalTitle');
    const passwordHelp = document.getElementById('passwordHelp');
    
    if (username) {
        // 编辑模式
        modalTitle.textContent = '编辑用户';
        passwordHelp.style.display = 'block';
        
        // 获取用户数据
        currentUser = usersList.find(u => u.username === username);
        
        // 填充表单
        document.getElementById('username').value = currentUser.username;
        document.getElementById('username').disabled = true;
        document.getElementById('password').value = '';
        document.getElementById('role').value = currentUser.role || 'user';
        document.getElementById('isActive').checked = currentUser.is_active !== false;
    } else {
        // 添加模式
        modalTitle.textContent = '添加用户';
        passwordHelp.style.display = 'none';
        currentUser = null;
        
        // 清空表单
        document.getElementById('username').value = '';
        document.getElementById('username').disabled = false;
        document.getElementById('password').value = '';
        document.getElementById('role').value = 'user';
        document.getElementById('isActive').checked = true;
    }
    
    userModal.show();
}

// 保存用户
async function saveUser() {
    // 获取表单数据
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const role = document.getElementById('role').value;
    const isActive = document.getElementById('isActive').checked;
    
    if (!username) {
        showAlert('warning', '请输入用户名');
        return;
    }
    
    if (!currentUser && !password) {
        showAlert('warning', '请输入密码');
        return;
    }
    
    const userData = {
        username,
        role,
        is_active: isActive
    };
    
    if (password) {
        userData.password = password;
    }
    
    try {
        const response = await fetch('/api/users', {
            method: currentUser ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            userModal.hide();
            loadUsers();
            showAlert('success', currentUser ? '用户更新成功' : '用户添加成功');
        } else {
            showAlert('danger', `操作失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('保存用户失败:', error);
        showAlert('danger', `操作失败: ${error.message || '网络错误'}`);
    }
}

// 确认删除用户
function confirmDeleteUser(username) {
    document.getElementById('deleteUsername').textContent = username;
    currentUser = { username };
    deleteModal.show();
}

// 删除用户
async function deleteUser() {
    if (!currentUser || !currentUser.username) return;
    
    try {
        const response = await fetch(`/api/users?username=${currentUser.username}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            deleteModal.hide();
            loadUsers();
            showAlert('success', '用户删除成功');
        } else {
            showAlert('danger', `删除失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('删除用户失败:', error);
        showAlert('danger', `删除失败: ${error.message || '网络错误'}`);
    }
}

// 搜索用户
function searchUsers() {
    const keyword = document.getElementById('searchInput').value.trim().toLowerCase();
    
    if (!keyword) {
        displayUsers(usersList);
        return;
    }
    
    const filtered = usersList.filter(user => 
        user.username.toLowerCase().includes(keyword) || 
        (user.role && user.role.toLowerCase().includes(keyword))
    );
    
    displayUsers(filtered);
}

// 显示提醒消息
function showAlert(type, message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.role = 'alert';
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    document.querySelector('.content-container').insertBefore(alertDiv, document.querySelector('.content-container').firstChild);
    
    // 3秒后自动关闭
    setTimeout(() => {
        const bsAlert = new bootstrap.Alert(alertDiv);
        bsAlert.close();
    }, 3000);
}
</script>
{% endblock %} 